package com.dailyblue.java.standard.design.手撕MyBatisPlus;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class SqlSession implements InvocationHandler {
    private Class c;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String sql = "";
        String tableName = "";
        String columns = "";
        String values = "";
        String methodName = method.getName();
        if ("insert".equals(methodName)) {
            Object obj = args[0];
            tableName = obj.getClass().getSimpleName();
            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field f : fields) {
                String fieldName = f.getName();
                String getFieldMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                Method m1 = obj.getClass().getDeclaredMethod(getFieldMethodName);
                Object result = m1.invoke(obj);
                columns += fieldName + ",";
                values += "'" + result + "'" + ",";
            }
            columns = columns.substring(0, columns.length() - 1);
            values = values.substring(0, values.length() - 1);
            sql = "insert into " + tableName + "(" + columns + ") values(" + values + ")";
        }
        System.out.println("需要执行的SQL：" + sql);
        return null;
    }

    public <T> T getMapper(Class<T> c) {
        this.c = c;
        return (T) Proxy.newProxyInstance(c.getClassLoader(), new Class[]{c}, this);
    }
}
